package com.daykw.wenshu.task;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;

import com.daykw.wenshu.config.NutzDaoConfig;
import com.daykw.wenshu.model.CaseText;
import com.daykw.wenshu.model.CourtAdhocUrl;
import com.daykw.wenshu.utils.SpringContextHolder;

public class PaserArticleAdhocJob extends Thread {

	private static Logger logger = Logger.getLogger(PaserArticleAdhocJob.class);

	@Override
	public void run() {

		try {
			NutDao dao = SpringContextHolder.getBean(NutzDaoConfig.class);

			List<CourtAdhocUrl> ds = dao.query(CourtAdhocUrl.class, Cnd.wrap("handled = 'A'  and status=0 LIMIT 1000"));

			for (CourtAdhocUrl task : ds) {
				String docid = task.getDoc_id();
				CaseText caset = dao.fetch(CaseText.class, Cnd.where("doc_id", "=", docid));

				String html = caset.getHtml();
				String content = "";

				if (StringUtils.isEmpty(html)) {
					logger.info("html为空:" + docid);
					dao.update(CourtAdhocUrl.class, Chain.make("status", 3), Cnd.where("doc_id", "=", docid));
					continue;
				}
				content = html.replace("\\", "");
				String cc = "";
				if (content.indexOf("<pstyle") >= 0 || content.indexOf("<spanstyle") >= 0) {
					content = content.replace("<pstyle", "<p style");
					content = content.replace("<spanstyle", "<span style");
					content = content.replace("”", "'");
					Document doc = Jsoup.parse(content);

					List<Element> tn = doc.getElementsByTag("p");
					for (Element tt : tn) {

						cc = cc + tt.text() + "_|_";
					}
					cc = cc.replace("\r\n", "_|_");
				} else {
					content = content.replace("”", "'");
					Document doc = Jsoup.parse(content);

					List<Element> tn = doc.getElementsByTag("div");
					for (Element tt : tn) {

						cc = cc + tt.text() + "_|_";
					}
					cc = cc.replace("\r\n", "_|_");

				}
				cc = cc.replace("p t ” >", "");
				int txt_len = cc.length();
				dao.update(CaseText.class, Chain.make("txt", cc).add("txt_len", txt_len),
						Cnd.where("doc_id", "=", docid));

				dao.update(CourtAdhocUrl.class, Chain.make("status", 2), Cnd.where("doc_id", "=", docid));
				logger.info("解析完毕:" + docid);
			}
			logger.info("处理完毕" + ds.size());
		} catch (Exception e) {
			logger.error("", e);
		}

	}

}
